class CarsController < ApplicationController
  # GET /cars
  # GET /cars.xml
  def index
    @cars = Car.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @cars }
    end
  end

  # GET /cars/1
  # GET /cars/1.xml
  def show
    @car = Car.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @car }
    end
  end

  # GET /cars/new
  # GET /cars/new.xml
  def new
    @car = Car.new
    @car.user = current_user
    
    @car_brands = CarBrand.find(:all, :order => :name)
    @car_models = @car_brands[0].car_models
    
    @years = []
    (1960..2011).each do |i|
      @years << i
    end
    @years.reverse!
    
    @engine_types = EngineType.find(:all, :order => :name)
    @gearbox_types = GearboxType.find(:all, :order => :name)    

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @car }
    end
  end
  
  def update_car_model_select
    car_models = CarModel.where(:car_brand_id => params[:id]).order(:name) unless params[:id].blank?
    render :partial => "car_models", :locals => { :car_models => car_models }    
  end  

  # GET /cars/1/edit
  def edit
    @car = Car.find(params[:id])
    
    @car_brands = CarBrand.find(:all, :order => :name)
    @car_models = @car_brands[0].car_models
    
    @years = []
    (1960..2011).each do |i|
      @years << i
    end
    @years.reverse!
    
    @engine_types = EngineType.find(:all, :order => :name)
    @gearbox_types = GearboxType.find(:all, :order => :name)        
  end

  # POST /cars
  # POST /cars.xml
  def create
    @car = Car.new(params[:car])
    @car.car_model_id = params[:car_model_id]

    respond_to do |format|
      if @car.save
        format.html { redirect_to(@car, :notice => 'Car was successfully created.') }
        format.xml  { render :xml => @car, :status => :created, :location => @car }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @car.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /cars/1
  # PUT /cars/1.xml
  def update
    @car = Car.find(params[:id])

    respond_to do |format|
      if @car.update_attributes(params[:car])
        format.html { redirect_to(@car, :notice => 'Car was successfully updated.') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @car.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /cars/1
  # DELETE /cars/1.xml
  def destroy
    @car = Car.find(params[:id])
    @car.destroy

    respond_to do |format|
      format.html { redirect_to(cars_url) }
      format.xml  { head :ok }
    end
  end
end
